package com.zifeng.utils;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.net.URISyntaxException;

/**
 * p2p客户端
 * 
 * @author zifeng
 *
 */
@Component
public class P2PClient {
	@Autowired
	P2PMessageHandler p2pMessageHandler;
	public void connectToPeer(String addr) {
		try {
			final WebSocketClient socketClient = new WebSocketClient(new URI(addr)) {
				public void onOpen(ServerHandshake serverHandshake) {
					p2pMessageHandler.write(this, p2pMessageHandler.queryLatestBlockMsg());
					p2pMessageHandler.getSockets().add(this);
				}
				/**
				 * 接收到消息时触发
				 * @param msg
				 */
				public void onMessage(String msg) {
					p2pMessageHandler.handleMessage(this, msg, p2pMessageHandler.getSockets());
				}
				public void onClose(int i, String msg, boolean b) {
					p2pMessageHandler.getSockets().remove(this);
					System.out.println("connection closed");
				}
				public void onError(Exception e) {
					p2pMessageHandler.getSockets().remove(this);
					System.out.println("connection failed");
				}
			};
			socketClient.connect();
		} catch (URISyntaxException e) {
			System.out.println("p2p connect is error:" + e.getMessage());
		}
	}
}
